import cv2
import face_recognition

# 初始化摄像头
video_capture = cv2.VideoCapture(0)

# 初始化人数统计变量
total_people = 0

while True:
    # 获取视频帧
    ret, frame = video_capture.read()
    if not ret:
        print("无法获取视频帧")
        break

    # 转换颜色空间（face_recognition需要RGB格式）
    rgb_frame = frame[:, :, ::-1]

    # 人脸检测（使用HOG模型，适合CPU运行）
    face_locations = face_recognition.face_locations(rgb_frame, model="hog")
    
    # 统计当前人数
    current_people = len(face_locations)
    
    # 更新总人数（这里简单显示当前人数，实际需要跟踪需要更复杂逻辑）
    if current_people > total_people:
        total_people = current_people

    # 在画面上标注人脸框和计数
    for (top, right, bottom, left) in face_locations:
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

    # 显示统计信息
    cv2.putText(frame, f"Current: {current_people}", (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
    cv2.putText(frame, f"Peak: {total_people}", (10, 60),
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)

    # 显示画面
    cv2.imshow('Face Recognition', frame)

    # 按Q退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
video_capture.release()
cv2.destroyAllWindows()